package org.example.mallchat.common.intecepter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import org.example.mallchat.common.domain.local.RequestInfo;
import org.example.mallchat.common.thread.ThreadLocalHandler;
import org.example.mallchat.service.LoginService;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author: zzh
 * @date: 2024/12/22 16:20:36
 * @version: 1.0
 */
@Order(1)//拦截器的顺序，越小越先执行
@Component//收集信息拦截器 ，请求就不需要request中拿了，直接公共ThreadLocal拿，一次请求就拿，请求响应后移除！
public class CollectIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        Long uid = (Long) request.getAttribute("uid");
        // hutool获取ip
        String clientIP = ServletUtil.getClientIP(request);
        // 存放到ThreadLocal中
        ThreadLocalHandler.setRequestInfo(new RequestInfo(uid.toString(), clientIP));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求响应后移除!!
        ThreadLocalHandler.remove();
    }

}
